<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <template v-slot="{ data }">
          <el-row style="width: 100%;height: auto;align-items: center;" type="flex" jusitify="space-between">
            <el-col :span="10">{{ data.name }}</el-col>
            <el-col :span="14" style="text-align: right;">
              <span class="tree-menu">{{ data.managerName }}</span>
              <el-dropdown trigger="click" style="margin-left: 20px;" @command="handleDept($event, data.id)">
                <span class="el-dropdown-link">
                  操作
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="change">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 弹窗组件 -->
    <add-depts ref="addDept" @addDepartment="getList" :showDialog.sync="showDialog" :current-node-id="currentNodeId" />
  </div>
</template>
<script>
import { getDepartment, delDepartment } from '@/api/department'
import { ListToTree } from '@/utils'
import AddDepts from './components/add-depts.vue'

export default {
  name: 'Department',
  components: { AddDepts },
  data() {
    return {
      // 存储当前点击的id
      currentNodeId: null,
      // 数据属性
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      showDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const result = await getDepartment()
      this.depts = ListToTree(result, 0)
    },
    handleDept(type, id) {
      if (type === 'add') {
        // 新增
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'change') {
        // 编辑
        this.showDialog = true
        this.currentNodeId = id
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else if (type === 'del') {
        // 删除
        this.$confirm('是否要删除').then(async() => {
          await delDepartment(id)
          this.$message.success('删除成功')
          this.getList()
        }).catch(err => {
          this.$message.error(err)
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 100px;
  font-size: 15px;

  :deep(.el-tree-node__children) {
    border-top: 1px dashed #e3e3e3;

    & :first-child {
      border-top: none;
    }
  }

  .tree-menu {
    width: 50px;
    text-align: left;
  }
}
</style>
